package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.endpoint.RefreshEndpoint;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.config.BindingProperties;
import org.springframework.cloud.stream.config.BindingServiceProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Map;

@RestController
@EnableBinding(StreamListenConfigRegistrar.ConfigRefreshChanel.class)
public class StreamListenConfigRegistrar {

    @Autowired
    private BindingServiceProperties bindingServiceProperties;

    @Autowired
    private ConfigRefreshChanel configRefreshChanel;

    /**
     * 事件发布者
     */
    @Autowired
    private RefreshEndpoint refreshEndpoint;

    /**
     * 配置管道绑定目的地，自动化，约定配置
     */
    @PostConstruct
    public void initConfig(){
        BindingProperties bindingProperties = new BindingProperties();
        bindingProperties.setDestination("searchConfigExchange");
        Map<String, BindingProperties> bindings = bindingServiceProperties.getBindings();
        bindings.put("searchConfigInput",bindingProperties);
        bindings.put("searchConfigOutput",bindingProperties);

    }

    /**
     * 刷新配置接口
     * @return
     */
    @GetMapping("/config/refresh")
    public ResponseEntity<String> publish() {
        boolean ok = configRefreshChanel.searchConfigOutput().send(MessageBuilder.withPayload("refresh config").build());
        return ResponseEntity.ok("config is refresh "+ok+"!");
    }

    /**
     * 消息订阅刷新配置
     * @param msg
     */
    @StreamListener(ConfigRefreshChanel.IN)
    public void subscribe(String msg) {
        System.out.println(msg);
        refreshEndpoint.refresh();
    }


    /**
     * 通道声明
     */
    public interface ConfigRefreshChanel {

        String IN = "searchConfigInput";

        String OUT = "searchConfigOutput";

        @Input(IN)
        SubscribableChannel searchConfigInput();

        @Output(OUT)
        MessageChannel searchConfigOutput();
    }

}
